package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.Pharmacist;
import com.example.exception.CustomException;
import com.example.mapper.PharmacistMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 张比特
 * @Data: 2024/8/28 下午9:10
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class PharmacistService {

    @Resource
    private PharmacistMapper pharmacistMapper;

    /**
     * 新增
     */
    public void add(Pharmacist pharmacist) {
        Pharmacist dbPharmacist = pharmacistMapper.selectByUsername(pharmacist.getUsername());
        if (ObjectUtil.isNotNull(dbPharmacist)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        } else {
            if (pharmacist.getPassword().isEmpty()) {
                pharmacist.setPassword(Constants.USER_DEFAULT_PASSWORD);
            }
            pharmacist.setRole("PHARMACIST");
            pharmacistMapper.insert(pharmacist);
        }
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        pharmacistMapper.deleteById(id);
    }

    /**
     * 修改
     */
    public void updateById(Pharmacist pharmacist) {
        pharmacistMapper.updateById(pharmacist);
    }

    /**
     * 根据ID查询
     */
    public Pharmacist selectById(Integer id) {
        return pharmacistMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Pharmacist> selectAll(Pharmacist pharmacist) {
        return pharmacistMapper.selectAll(pharmacist);
    }

    /**
     * 分页查询
     */
    public PageInfo<Pharmacist> selectPage(Pharmacist pharmacist, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Pharmacist> list = pharmacistMapper.selectAll(pharmacist);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public Account login(Account account) {
        Account dbPharmacist = pharmacistMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbPharmacist)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST);
        }
        if (!account.getPassword().equals(dbPharmacist.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        return dbPharmacist;
    }


}
